<?php
	/**
	* @File name:	model.php
	* @Desription:	modelbase
	* @Author:	 	jinxin<jx@178.com>   
	* @Date:	 	Thu Aug 11 18:48:05 CST 2011
	* @Copyright 	Copytright (c) 2008-2011 178.COM Co., Ltd.
	* @version	 	$Id $
	*/
	
	class model {
		public static $getInstence = array();
		public $db;
		public static $cur_db = 'admin';
		
		public function __construct(){
			$this->db = db::getInstence(self::$cur_db);
		}
		
		public static function factory($modelName,$db = ''){
			if (!key_exists($modelName,self::$getInstence)){
				if ($db != ''){
					self::$cur_db = $db;
				}
				self::$getInstence[$modelName] = new $modelName();
			}
			return self::$getInstence[$modelName];
		}
		
		public function selectPage($sql,$page,$pagesize){
			$sql = preg_replace("/\n+/"," ", $sql);
			$regx = "|select\s+(.*)\s+from\s+(.*)|Ui";
			$sqlCount = preg_replace($regx,
			'
	select count(*) as rcount from \\2
				',
			$sql, 1);
			$count = $this->db->fetchField($sqlCount,'rcount');
			$pageCount = (int)floor($count/$pagesize);
			$pageCount += ($count%$pagesize==0) ? 0 : 1;
			$page = ($page<1) ? 1 : $page;
			$pageCount = $pageCount < 1 ? 1: $pageCount;
			$page = ($page>$pageCount) ? $pageCount:$page;
			$start = ($page -1)*$pagesize;
			$ret['rows'] = $count > 0 ? $this->db->fetchAll($sql." LIMIT {$start},$pagesize") : array();
			$ret['pageInfo'] = array("count"=>$count,
				"pagecount"=>$pageCount,
				"page"=>$page,
				"pagesize"=>$pagesize
			);
			return $ret;
		}
	}
	